﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ICeFramework.Common.DataLayer;
using ICeFramework.DataAccess.DataLayer.Enums;

namespace ICeFramework.DataAccess.DataLayer.MsSQL
{
    public class InsertCommand : DBCommand
    {

        public override DBCommandType CommandType
        {
            get { return DBCommandType.Insert; }
        }

        public InsertCommand(string tableName, IDbTransaction transaction) :
            base(tableName, transaction)
        {

        }

        public override string BuildCommandText(string parameterToken)
        {
            StringBuilder valuesClause = new StringBuilder();
            StringBuilder commandText = new StringBuilder();

            commandText.Append("INSERT INTO ");
            commandText.Append(base.EntityName);
            if (Parameters.ParametesKey.Length > 0)
            {
                commandText.Append(" (");
            }

            foreach (DataParameter param in Parameters)
            {
                commandText.Append(string.Format("[{0}]", param.SourceColumn));
                commandText.Append(", ");
                valuesClause.Append(parameterToken);
                valuesClause.Append(param.ParameterName);
                valuesClause.Append(", ");
                if (param.ParameterName.IndexOf(parameterToken) != 0)
                {
                    param.ParameterName = parameterToken + "[" + param.ParameterName + "]";
                }
            }

            if (Parameters.ParametesKey.Length > 0)
            {
                commandText.Remove(commandText.Length - 2, 2);
            }

            if (valuesClause.Length >= 2)
            {
                valuesClause.Remove(valuesClause.Length - 2, 2);
            }
            if (valuesClause.Length > 0)
            {
                commandText.Append(") VALUES (");
                commandText.Append(valuesClause.ToString());
                commandText.Append(")");
            }

            return commandText.ToString();
        }

        public override string BuildPagingCommandText(string parameterToken, int pageIndex, int pageSize)
        {
            throw new NotSupportedException();
        }
    }
}
